<template>
  <div class="main">
    <div class="main-title">
      <h4 v-text="isEdit ? '城市合伙人编辑' : '城市合伙人新建'"></h4>
      <div class="btn-box">
        <el-button
          class="filter-item"
          type="success"
          :loading="btnLoading"
          @click="save"
        >保存</el-button>
        <el-button
          class="filter-item"
          type="primary"
          plain
          @click="$router.back()"
        >返回</el-button>
      </div>
    </div>
    <div class="section partner-section">
      <el-tabs
        v-model="activeName"
        style="padding:20px; background:#FFF"
        type="card"
      >
        <el-tab-pane
          label="城市合伙人信息"
          name="first"
        >
          <el-form
            :model="formData"
            :rules="formRules"
            size="medium"
            ref="form"
            label-width="150px"
          >
            <el-form-item
              label="名称:"
              prop="packageRequest.name"
            >
              <el-input v-model="formData.packageRequest.name"></el-input>
            </el-form-item>
            <el-form-item
              label="副标题:"
              prop="packageRequest.subTitle"
            >
              <el-input v-model="formData.packageRequest.subTitle"></el-input>
            </el-form-item>
            <el-form-item
              label="商品:"
              prop="packageGoodsList"
            >
              <el-button
                type="primary"
                plain
                @click="chooseGoods"
                :disabled="!!isEdit"
              >选择商品</el-button>
            </el-form-item>
            <el-form-item v-if="formData.packageGoodsList.length > 0">
              <div
                v-for="(goods, index) of formData.packageGoodsList"
                style="border: 0px solid #eee; margin-bottom: 25px"
              >
                <el-tag
                  :key="goods.id"
                  :closable="!isEdit"
                  @close="delGoods(index)"
                >{{goods.goodsName}}</el-tag>
                <el-checkbox
                  :true-label="0"
                  :false-label="1"
                  v-model="goods.packageGoodsType"
                  :disabled="!!isEdit"
                  @change="reValidate"
                >设为赠品</el-checkbox>
                <el-table
                  v-if="goods.goodsAttr.length"
                  :data="goods.goodsAttr"
                  border
                  highlight-current-row
                >
                  <el-table-column
                    v-for="(item, index) in [{id: 'attrId1',prop: 'attrValue1'},{id:'attrId2',prop: 'attrValue2'},{id:'attrId3',prop: 'attrValue3'},{id:'attrId4',prop: 'attrValue4'},{id:'attrId5',prop: 'attrValue5'},{id:'attrId6',prop: 'attrValue6'}]"
                    v-if="goods.goodsAttr[0][item.id]"
                    :key="index"
                    align="center"
                    :label="'属性值'+(index+1)"
                    :prop="item.prop"
                    min-width="100px"
                  >
                  </el-table-column>
                  <!--<el-table-column align="center" label="财务价">
                                <template slot-scope="scope">
                                    <el-form-item :prop="'packageGoodsList.'+index+'.goodsAttr['+scope.$index+'].financePrice'" :rules="commonRules.priceRuleNull" style="margin: 20px 0">
                                        <el-input type="number" v-model="scope.row.financePrice" style="width: 100%"></el-input>
                                    </el-form-item>
                                </template>
                            </el-table-column>
                            <el-table-column align="center" label="成本价">
                                <template slot-scope="scope">
                                    <el-form-item :prop="'packageGoodsList.'+index+'.goodsAttr['+scope.$index+'].costPrice'"  :rules="commonRules.priceRuleNull" style="margin: 20px 0">
                                        <el-input type="number" v-model="scope.row.costPrice" style="width: 100%"></el-input>
                                    </el-form-item>
                                </template>
                            </el-table-column>-->
                  <el-table-column
                    align="center"
                    label="市场价"
                  >
                    <template slot-scope="scope">
                      <el-form-item
                        :prop="'packageGoodsList.'+index+'.goodsAttr['+scope.$index+'].marketValue'"
                        :rules="commonRules.priceRule"
                        style="margin: 30px 0"
                      >
                        <el-input
                          type="number"
                          v-model="scope.row.marketValue"
                          style="width: 100%"
                        ></el-input>
                      </el-form-item>
                    </template>
                  </el-table-column>
                  <el-table-column
                    align="center"
                    label="兰蜜价"
                  >
                    <template slot-scope="scope">
                      <el-form-item
                        :prop="'packageGoodsList.'+index+'.goodsAttr['+scope.$index+'].price'"
                        :rules="commonRules.priceRule"
                        style="margin: 30px 0"
                      >
                        <el-input
                          type="number"
                          v-model="scope.row.price"
                          style="width: 100%"
                          @change="calcOtherPrice(index, scope.$index)"
                        ></el-input>
                      </el-form-item>
                    </template>
                  </el-table-column>
                  <el-table-column
                    align="center"
                    label="大区价"
                  >
                    <template slot-scope="scope">
                      <el-form-item
                        :prop="'packageGoodsList.'+index+'.goodsAttr['+scope.$index+'].regionPrice'"
                        :rules="{required: true, message: '不能为空', trigger: 'change'}"
                        style="margin: 20px 0"
                      >
                        <el-input
                          type="number"
                          placeholder="自动生成"
                          v-model="scope.row.regionPrice"
                          style="width: 100%"
                          disabled
                        ></el-input>
                      </el-form-item>
                    </template>
                  </el-table-column>
                  <el-table-column
                    align="center"
                    label="董事价"
                  >
                    <template slot-scope="scope">
                      <el-form-item
                        :prop="'packageGoodsList.'+index+'.goodsAttr['+scope.$index+'].directorPrice'"
                        :rules="{required: true, message: '不能为空', trigger: 'change'}"
                        style="margin: 20px 0"
                      >
                        <el-input
                          type="number"
                          placeholder="自动生成"
                          v-model="scope.row.directorPrice"
                          style="width: 100%"
                          disabled
                        ></el-input>
                      </el-form-item>
                    </template>
                  </el-table-column>
                  <!--<el-table-column align="center" label="佣金类型" min-width="98px">
                                <template slot-scope="scope">
                                    <el-form-item :prop="'packageGoodsList.'+index+'.goodsAttr['+scope.$index+'].commissionType'" :rules="{required: true, message: '不能为空', trigger: 'change'}" style="margin: 30px 0">
                                        <el-select v-model="scope.row.commissionType">
                                            <el-option :key="1" label="数值(元)" :value="1"></el-option>
                                            <el-option :key="2" label="比例(%)" :value="2"></el-option>
                                        </el-select>
                                    </el-form-item>
                                </template>
                            </el-table-column>
                            <el-table-column align="center" label="佣金数值">
                                <template slot-scope="scope">
                                    <el-form-item :prop="'packageGoodsList.'+index+'.goodsAttr['+scope.$index+'].commission'" :rules="scope.row.commissionType===1?commonRules.priceRule : commonRules.percentRule" style="margin: 30px 0">
                                        <el-input type="number" v-model="scope.row.commission" style="width: 100%"></el-input>
                                    </el-form-item>
                                </template>
                            </el-table-column>-->
                  <el-table-column
                    align="center"
                    label="最高佣金"
                  >
                    <template slot-scope="scope">
                      <el-form-item
                        :prop="'packageGoodsList.'+index+'.goodsAttr['+scope.$index+'].maximumCommission'"
                        :rules="commonRules.priceRuleZero"
                        style="margin: 30px 0"
                      >
                        <el-input
                          type="number"
                          placeholder="小于兰蜜价"
                          v-model="scope.row.maximumCommission"
                          style="width: 100%"
                          @change="calcOtherPrice(index, scope.$index)"
                        ></el-input>
                      </el-form-item>
                    </template>
                  </el-table-column>
                  <el-table-column
                    align="center"
                    label="库存数"
                    prop="totalSkuNumber"
                    min-width="100px"
                  >
                    <template slot-scope="scope">
                      {{scope.row.totalSkuNumber}}
                      <div
                        v-if="!scope.row.totalSkuNumber"
                        style="color: red"
                      >库存不足</div>
                    </template>
                  </el-table-column>
                  <el-table-column
                    align="center"
                    label="已售"
                    prop="soldNumber"
                    min-width="100px"
                  ></el-table-column>
                  <!--<el-table-column align="center" label="库存数" min-width="90px">
                                <template slot-scope="scope">
                                    可分配：{{scope.row.totalSkuNumber}}<br/>
                                    已分配：{{(scope.row.distributedSkuNumber||0)+(scope.row.soldNumber||0)}}<br/>
                                    <el-form-item v-if="scope.row.totalSkuNumber+(scope.row.distributedSkuNumber||0)" :prop="'packageGoodsList.'+index+'.goodsAttr['+scope.$index+'].skuNumber'" :rules="commonRules.skuNumberRule" style="margin: 0 0 30px">
                                        <el-input-number v-model="scope.row.skuNumber" :disabled="formData.packageRequest.type === 3" :min="1" :max="scope.row.totalSkuNumber+(scope.row.distributedSkuNumber||0)" :precision="0" :controls="false" style="width: 100%"></el-input-number>
                                    </el-form-item>
                                    <span v-else style="color: red">库存不足</span>
                                </template>
                            </el-table-column>
                            <el-table-column align="center" label="数量" min-width="70px">
                                <template slot-scope="scope">
                                    <el-form-item :prop="'packageGoodsList.'+index+'.goodsAttr['+scope.$index+'].number'" :rules="commonRules.numberRule" style="margin: 30px 0">
                                        <el-input type="number" v-model="scope.row.number" style="width: 100%"></el-input>
                                    </el-form-item>
                                </template>
                            </el-table-column>-->
                  <!--<el-table-column align="center" label="是否上架" width="80">
                                <template slot-scope="scope">
                                    <el-switch
                                            v-model="scope.row.upshelf"
                                            active-color="#13ce66"
                                            inactive-color="#ff4949"
                                            :active-value="1"
                                            :inactive-value="0">
                                    </el-switch>
                                </template>
                            </el-table-column>-->
                  <el-table-column
                    v-if="!isEdit && goods.goodsAttr.length>1"
                    align="center"
                    label="操作"
                    width="60"
                    fixed="right"
                  >
                    <template slot-scope="scope">
                      <a
                        href="javascript: void(0);"
                        class="el-icon-remove"
                        @click="delAttrVal(goods.goodsAttr, scope.$index)"
                      ></a>
                    </template>
                  </el-table-column>
                </el-table>
              </div>
            </el-form-item>

            <el-form-item
              label="商品单位:"
              prop="partnerGoods.goodsCounts"
              :rules="commonRules.numberRule"
            >
              一箱 =
              <el-input
                type="number"
                v-model="formData.partnerGoods.goodsCounts"
                style="width: 150px"
              >
                <template slot="append">件</template>
              </el-input>
            </el-form-item>
            <!--<el-form-item label="套餐库存:" prop="packageRequest.packageNumber">
                    <el-input type="number" v-model="formData.packageRequest.packageNumber">
                        <template slot="append">箱</template>
                    </el-input>
                </el-form-item>-->
            <el-form-item
              v-show="false"
              label="礼品单位:"
              prop="partnerGoods.giftCounts"
              :rules="commonRules.numberRule"
            >
              一箱 =
              <el-input
                type="number"
                v-model="formData.partnerGoods.giftCounts"
                style="width: 150px"
              >
                <template slot="append">件</template>
              </el-input>
            </el-form-item>
            <el-form-item
              label="选择礼品数:"
              prop="partnerGoods.selectGiftCount"
            >
              <el-input
                type="number"
                :disabled="!presentGoodsList.length"
                :min="1"
                :max="presentGoodsList.length"
                v-model="formData.partnerGoods.selectGiftCount"
                style="width: 180px"
              >
                <template slot="append">(赠品数: {{presentGoodsList.length}})</template>
              </el-input>
            </el-form-item>
            <el-form-item
              v-for="(item, index) in tempPresentList"
              :key="index"
              label="礼品单位:"
              :rules="commonRules.numberRule"
            >
              {{item.name}} 一箱
              <el-input
                type="number"
                min="1"
                v-model="item.giftPieceNumber"
                style="width: 150px"
              >
                <template slot="append">件</template>
              </el-input>
            </el-form-item>
            <!--<el-form-item label="礼品库存:" prop="packageRequest.presentSelectedNum">
                    <el-input type="number" v-model="formData.packageRequest.presentSelectedNum">
                        <template slot="append">箱</template>
                    </el-input>
                </el-form-item>-->
            <el-form-item
              label="购买等级:"
              prop="buyRoleList"
            >
              <el-checkbox-group
                v-model="formData.buyRoleList"
                :disabled="!!isEdit"
                @change="getPartnerGoodsDetailList"
              >
                <!--<el-checkbox label="普通" :value="0"></el-checkbox>
                        <el-checkbox label="兰蜜" :value="1"></el-checkbox>-->
                <el-checkbox label="2">大区</el-checkbox>
                <el-checkbox label="3">董事</el-checkbox>
              </el-checkbox-group>
            </el-form-item>
            <el-form-item
              v-if="formData.buyRoleList.length"
              label="数据设置:"
              prop="partnerGoodsDetailList"
            >
              <el-table
                :data="formData.partnerGoodsDetailList "
                :span-method="settingDataSpanMethod"
                border
                style="width: 100%; margin-top: 20px"
              >
                <el-table-column
                  align="center"
                  prop="role"
                  label="用户等级"
                  width="100"
                >
                  <template slot-scope="scope">
                    <span v-if="scope.row.role==0">普通</span>
                    <span v-if="scope.row.role==1">兰蜜</span>
                    <span v-if="scope.row.role==2">大区</span>
                    <span v-if="scope.row.role==3">董事</span>
                  </template>
                </el-table-column>
                <el-table-column
                  align="center"
                  prop="type"
                  label="类型"
                >
                  <template slot-scope="scope">
                    <span v-if="scope.row.type===1">首购</span>
                    <span v-if="scope.row.type===2">补货</span>
                  </template>
                </el-table-column>
                <el-table-column
                  align="center"
                  label="数量"
                >
                  <template slot-scope="scope">
                    <el-form-item
                      label-width="0"
                      :prop="'partnerGoodsDetailList['+scope.$index+'].num'"
                      :rules="commonRules.numberRule"
                    >
                      <el-input
                        type="number"
                        v-model="scope.row.num"
                      ></el-input>
                    </el-form-item>
                  </template>
                </el-table-column>
                <el-table-column
                  align="center"
                  label="佣金"
                >
                  <el-table-column
                    align="center"
                    label="推荐大区"
                  >
                    <template slot-scope="scope">
                      <el-form-item
                        label-width="0"
                        :prop="'partnerGoodsDetailList['+scope.$index+'].recommAreaCommission'"
                        :rules="commonRules.priceRuleZero"
                      >
                        <el-input
                          type="number"
                          v-model="scope.row.recommAreaCommission"
                        ></el-input>
                      </el-form-item>
                    </template>
                  </el-table-column>
                  <el-table-column
                    align="center"
                    label="直招董事"
                  >
                    <template slot-scope="scope">
                      <el-form-item
                        label-width="0"
                        :prop="'partnerGoodsDetailList['+scope.$index+'].directorCommission'"
                        :rules="commonRules.priceRuleZero"
                      >
                        <el-input
                          type="number"
                          v-model="scope.row.directorCommission"
                        ></el-input>
                      </el-form-item>
                    </template>
                  </el-table-column>
                  <el-table-column
                    align="center"
                    label="推荐董事"
                  >
                    <template slot-scope="scope">
                      <el-form-item
                        label-width="0"
                        :prop="'partnerGoodsDetailList['+scope.$index+'].recommDirectorCommission'"
                        :rules="commonRules.priceRuleZero"
                      >
                        <el-input
                          type="number"
                          v-model="scope.row.recommDirectorCommission"
                        ></el-input>
                      </el-form-item>
                    </template>
                  </el-table-column>
                </el-table-column>
                <el-table-column
                  align="center"
                  prop="presentNum"
                  label="赠品（按月累计）"
                  width="200"
                >
                  <template slot-scope="scope">
                    <el-col :span="11">
                      <el-form-item
                        label-width="0"
                        :prop="'partnerGoodsDetailList['+scope.$index+'].ruleJson.packageNum'"
                        :rules="commonRules.numberRuleZero"
                      >
                        <el-input
                          type="number"
                          v-model="scope.row.ruleJson.packageNum"
                        ></el-input>
                      </el-form-item>
                    </el-col>
                    <el-col
                      class="line"
                      :span="2"
                      style="margin-top: 30px"
                    >:</el-col>
                    <el-col :span="11">
                      <el-form-item
                        label-width="0"
                        :prop="'partnerGoodsDetailList['+scope.$index+'].ruleJson.presentNum'"
                        :rules="commonRules.numberRuleZero"
                      >
                        <el-input
                          type="number"
                          v-model="scope.row.ruleJson.presentNum"
                        ></el-input>
                      </el-form-item>
                    </el-col>
                  </template>
                </el-table-column>
                <el-table-column
                  align="center"
                  label="赠送大区名额"
                >
                  <template slot-scope="scope">
                    <el-form-item
                      label-width="0"
                      :prop="'partnerGoodsDetailList['+scope.$index+'].bigAreas'"
                      :rules="commonRules.numberRuleZero"
                    >
                      <el-input
                        type="number"
                        v-model="scope.row.bigAreas"
                      ></el-input>
                    </el-form-item>
                  </template>
                </el-table-column>
              </el-table>
            </el-form-item>
            <el-form-item
              label="零售价:"
              prop="packageRequest.marketValue"
            >
              <el-input
                type="number"
                v-model="formData.packageRequest.marketValue"
              ></el-input>
            </el-form-item>
            <!--
                <el-form-item label="兰蜜价:" prop="packageRequest.price">
                    <el-input type="number" v-model="formData.packageRequest.price" @change="calcPrice"></el-input>
                </el-form-item>-->
            <el-form-item
              label="大区价:"
              prop="packageRequest.regionPrice"
              v-if="formData.buyRoleList.some(item=>item==2)"
            >
              <el-input
                type="number"
                v-model="formData.packageRequest.regionPrice"
              ></el-input>
            </el-form-item>
            <el-form-item
              label="董事价:"
              prop="packageRequest.directorPrice"
              v-if="formData.buyRoleList.some(item=>item==3)"
            >
              <el-input
                type="number"
                v-model="formData.packageRequest.directorPrice"
              ></el-input>
            </el-form-item>
            <el-form-item
              label="运费模板:"
              prop="packageRequest.freightTemplateId"
            >
              <el-select
                v-model="formData.packageRequest.freightTemplateId"
                placeholder="请选择"
                filterable
                clearable
              >
                <el-option
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                  v-for="item in freightList"
                ></el-option>
              </el-select>
            </el-form-item>
            <!--<el-form-item label="佣金类型:" prop="packageRequest.commissionType">
                    <el-select v-model="formData.packageRequest.commissionType">
                        <el-option :key="1" label="数值(元)" :value="1"></el-option>
                        <el-option :key="2" label="比例(%)" :value="2"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="佣金数值:" prop="packageRequest.commission">
                    <el-input type="number" v-model="formData.packageRequest.commission"></el-input>
                </el-form-item>
                <el-form-item label="最高佣金:" prop="packageRequest.maximumCommission" :rules="commonRules.priceRuleZero">
                    <el-input type="number" placeholder="须小于兰蜜价" v-model="formData.packageRequest.maximumCommission" @change="calcPrice"></el-input>
                </el-form-item>-->
            <el-form-item
              label="是否上架:"
              prop="packageRequest.upshelf"
            >
              <el-switch
                v-model="formData.packageRequest.upshelf"
                active-color="#13ce66"
                inactive-color="#ff4949"
                active-text="是"
                inactive-text="否"
                :active-value="1"
                :inactive-value="0"
              >
              </el-switch>
            </el-form-item>
            <el-form-item
              label="是否售卖:"
              prop="packageRequest.isSell"
            >
              <el-switch
                v-model="formData.packageRequest.isSell"
                active-color="#13ce66"
                inactive-color="#ff4949"
                active-text="是"
                inactive-text="否"
                :active-value="1"
                :inactive-value="0"
              >
              </el-switch>
            </el-form-item>
            <el-form-item
              label="套餐主图:"
              prop="packageRequest.image"
            >
              <el-upload
                class="avatar-uploader"
                accept="image/*"
                :action="upladUrl"
                name="file"
                :show-file-list="false"
                :before-upload="beforeUpload"
                :on-success="uploadSuccess"
              >
                <img
                  v-if="formData.packageRequest.image"
                  :src="formData.packageRequest.image"
                  class="avatar"
                >
                <i
                  v-else
                  class="el-icon-plus avatar-uploader-icon"
                ></i>
              </el-upload>
            </el-form-item>
            <el-form-item
              label="套餐图片:"
              prop="packageGalleryList"
            >
              <ul class="upload-img-list">
                <li
                  class="img-preview"
                  v-for="(item, index) of formData.packageGalleryList"
                >
                  <img
                    :src="item.url"
                    alt=""
                  >
                  <div class="img-preview-mask">
                    <div class="mask-btn">
                      <i
                        title="删除"
                        class="el-icon-delete"
                        @click="delImg(index)"
                      ></i>
                    </div>
                  </div>
                </li>
                <li>
                  <label class="upload-btn">
                    <input
                      type="file"
                      accept="image/*"
                      @change="uploadImg"
                    />
                    <i class="el-icon-plus"></i>
                  </label>
                </li>
              </ul>
            </el-form-item>
            <el-form-item
              label="套餐说明:"
              prop="packageRequest.remarks"
            >
              <el-input
                type="textarea"
                v-model="formData.packageRequest.remarks"
              ></el-input>
            </el-form-item>
            <el-form-item
              label="套餐故事:"
              prop="packageRequest.story"
            >
              <el-input
                type="textarea"
                v-model="formData.packageRequest.story"
              ></el-input>
            </el-form-item>
            <el-form-item
              label="套餐详情:"
              prop="packageRequest.intro"
            >
              <tinymce
                :height="360"
                v-model="formData.packageRequest.intro"
              ></tinymce>
            </el-form-item>
            <el-form-item>
              <el-button
                type="success"
                @click="save"
                :loading="btnLoading"
              >保存</el-button>
            </el-form-item>
          </el-form>
        </el-tab-pane>
        <el-tab-pane
          label="评论列表"
          name="second"
        >
          <CommontTable
            v-if='commontGoods.length > 0'
            :goods="commontGoods"
            :goodsType="3"
          />
        </el-tab-pane>
      </el-tabs>

    </div>
  </div>
</template>
<script>
import differenceBy from 'lodash/differenceBy'
import { regexp } from '../../../utils/tools'
import Tinymce from '@/components/Tinymce'
import { upload } from '../../../api/common'
import { getAllList } from '@/api/freight'
import CommontTable from '@/components/CommontTable'
export default {
  name: 'partnerEdit',
  props: {
    id: { default: '' }
  },
  components: {
    Tinymce,
    CommontTable
  },
  data() {
    const validNum = (rule, value, callback) => {
      if (!value) {
        return callback()
      }
      if (!/^[1-9]\d*$/.test(value)) {
        return callback(new Error('必须为正整数'))
      }
      let maxNum = this.formData.packageGoodsList.filter(
        item => item.packageGoodsType === 1
      ).length
      if (maxNum < 1) {
        return callback(new Error('请先选择商品'))
      }
      if (value > maxNum) {
        return callback(new Error('不能超过总商品(非赠品)数量'))
      }
      return callback()
    }
    const validSelectGiftCount = (rule, value, callback) => {
      console.log('rule, value, callback', rule, value, callback)
      if (!value) {
        return callback()
      }
      if (!/^[1-9]\d*$/.test(value)) {
        return callback(new Error('必须为正整数'))
      }
      let maxNum = this.presentGoodsList.length
      if (maxNum < 1) {
        return callback(new Error('请先选择商品'))
      }
      if (value > maxNum) {
        return callback(new Error('礼品数不可超过设置的赠品数'))
      }
      return callback()
    }
    const validDiscount = (rule, value, callback) => {
      if (value <= 0 || !/^([1-9]{1}|(\d\.\d))$/.test(value)) {
        return callback(new Error('必须为大于0小于10，最多保留1位小数'))
      }
      return callback()
    }
    const validPackageGoodsList = (rule, value, callback) => {
      let maxNum = this.formData.packageGoodsList.filter(
        item => item.packageGoodsType === 1
      ).length
      if (maxNum < 1) {
        return callback(new Error('请选择至少一个商品（非设置成赠品）'))
      }
      return callback()
    }
    const validPackageNumber = (rule, value, callback) => {
      if (value < 1) {
        return callback(new Error('必须大于0'))
      }
      if (this.formData.packageRequest.type === 3) {
        let skuNumArray = []
        this.formData.packageGoodsList.map(item => {
          if (item.packageGoodsType === 1 && item.goodsAttr.length) {
            let skuNum = 0
            item.goodsAttr.map(subItem => {
              skuNum =
                ((subItem.distributedSkuNumber || 0) + subItem.totalSkuNumber) /
                (this.formData.partnerGoods.goodsCounts || 1)
              skuNumArray.push(Math.floor(skuNum))
              // skuNum+=((subItem.distributedSkuNumber||0) + subItem.totalSkuNumber)partnerGoods
            })
            // skuNumArray.push(skuNum)
          }
        })
        let minNum = Math.min.apply(null, skuNumArray)
        if (minNum < 1) {
          return callback(new Error('存在0库存商品，请先移除'))
        } else if (value > minNum) {
          return callback(new Error('最大箱数为：' + minNum))
        }
      }

      return callback()
    }
    const validPresentNum = (rule, value, callback) => {
      if (this.formData.packageRequest.type === 3) {
        let skuNumArray = []
        this.formData.packageGoodsList.map(item => {
          if (item.packageGoodsType === 0 && item.goodsAttr.length) {
            let skuNum = 0
            item.goodsAttr.map(subItem => {
              skuNum =
                ((subItem.distributedSkuNumber || 0) + subItem.totalSkuNumber) /
                (this.formData.partnerGoods.giftCounts || 1)
              skuNumArray.push(Math.floor(skuNum))
              // skuNum+=((subItem.distributedSkuNumber||0) + subItem.totalSkuNumber)partnerGoods
            })
            // skuNumArray.push(skuNum)
          }
        })
        let minNum = Math.min.apply(null, skuNumArray)
        if (minNum < 1) {
          return callback(new Error('存在0库存赠品，请先移除'))
        } else if (value > minNum) {
          return callback(new Error('最大箱数为：' + minNum))
        }
      }

      return callback()
      /*if (!value) {
            return callback();
        }
        if (!/^([1-9]\d*|0)$/.test(value)) {
            return callback(new Error('必须为非负整数'));
        }
        let maxNum = this.formData.packageGoodsList.filter(item => item.packageGoodsType === 0).length;
        if (maxNum < 1) {
            return callback(new Error('请先选择商品并设置成赠品'));
        }
        if (value > maxNum) {
            return callback(new Error('不能超过总赠品数量'));
        }
        return callback();*/
    }
    return {
      commontGoods: [],
      activeName: 'first',
      tempGoodsCheck: [],
      tempPresentList: [],
      btnLoading: false,
      formData: {
        packageRequest: {
          name: '',
          type: 3,
          num: '',
          marketValue: '',
          price: '',
          regionPrice: '',
          directorPrice: '',
          commissionType: 1,
          commission: '',
          packagePricingType: 1,
          discount: '',
          isEnable: '',
          upshelf: 0,
          isSell: 0,
          isPurchaseLimit: 1,
          timeRange: [],
          userQuantity: '',
          image: '',
          remarks: '',
          story: '',
          intro: '',
          freightTemplateId: '' //运费模板
        },
        packageGalleryList: [],
        packageGoodsList: [],
        packageTagList: [],
        buyRoleList: [],
        goodsAttr: [],
        partnerGoods: {
          id: '',
          qualifyingGoodsId: '',
          buyRole: '',
          goodsCounts: 1,
          giftCounts: 1,
          selectGiftCount: 0
        },
        partnerGoodsDetailList: []
      },
      formRules: {
        'partnerGoods.selectGiftCount': [
          { required: true, message: '不能为空', trigger: 'change' },
          { validator: validSelectGiftCount, trigger: 'change' }
        ],
        'packageRequest.name': [
          { required: true, message: '不能为空', trigger: 'change' },
          { max: 100, message: '不能超过100字符', trigger: 'change' }
        ],
        packageGoodsList: [
          { required: true, message: '请选择商品', trigger: 'change' },
          { validator: validPackageGoodsList, trigger: 'change' }
        ],
        buyRoleList: [
          { required: true, message: '请选择用户类型', trigger: 'change' }
        ],
        'packageRequest.presentSelectedNum': [
          { validator: validPresentNum, trigger: 'change' }
        ],
        'packageRequest.num': [
          { required: true, message: '不能为空', trigger: 'change' },
          { validator: validNum, trigger: 'change' }
        ],
        'packageRequest.packageNumber': [
          { required: true, message: '不能为空', trigger: 'change' },
          { validator: validPackageNumber, trigger: 'change' }
        ],
        'packageRequest.marketValue': [
          { required: true, message: '不能为空', trigger: 'change' },
          {
            pattern: regexp.money,
            message: '价格必须大于0且最多两位小数',
            trigger: 'change'
          }
        ],
        'packageRequest.price': [
          { required: true, message: '不能为空', trigger: 'change' },
          {
            pattern: regexp.money,
            message: '价格必须大于0且最多两位小数',
            trigger: 'change'
          }
        ],
        'packageRequest.regionPrice': [
          { required: true, message: '不能为空', trigger: 'change' },
          {
            pattern: regexp.money,
            message: '价格必须大于0且最多两位小数',
            trigger: 'change'
          }
        ],
        'packageRequest.directorPrice': [
          { required: true, message: '不能为空', trigger: 'change' },
          {
            pattern: regexp.money,
            message: '价格必须大于0且最多两位小数',
            trigger: 'change'
          }
        ],
        'packageRequest.commission': [
          { required: true, message: '不能为空', trigger: 'change' },
          {
            pattern: regexp.money,
            message: '佣金必须大于0且最多两位小数',
            trigger: 'change'
          }
        ],
        'packageRequest.maximumCommission': [
          { required: true, message: '不能为空', trigger: 'change' },
          {
            pattern: regexp.money,
            message: '佣金必须大于0且最多两位小数',
            trigger: 'change'
          }
        ],
        'packageRequest.discount': [
          { required: true, message: '不能为空', trigger: 'change' },
          { validator: validDiscount, trigger: 'change' }
        ],
        'packageRequest.userQuantity': [
          { required: true, message: '不能为空', trigger: 'change' }
        ],
        'packageRequest.image': [
          { required: true, message: '不能为空', trigger: 'change' }
        ],
        packageGalleryList: [
          { required: true, message: '请上传套餐图片', trigger: 'change' }
        ],
        'packageRequest.remarks': [
          { required: true, message: '不能为空', trigger: 'change' }
        ],
        'packageRequest.story': [
          { required: true, message: '不能为空', trigger: 'change' }
        ],
        'packageRequest.intro': [
          { required: true, message: '不能为空', trigger: 'change' }
        ],
        'packageRequest.freightTemplateId': [
          { required: true, message: '不能为空', trigger: 'change' }
        ]
      },
      freightList: []
    }
  },
  computed: {
    isEdit() {
      return this.id && this.$route.name === 'activityPartnerEdit'
    },
    presentGoodsList() {
      if (!this.formData || !this.formData.packageGoodsList) {
        return []
      }
      if (!this.isEdit) {
        this.tempPresentList = []
      }
      return this.formData.packageGoodsList.filter(item => {
        if (!this.isEdit) {
          if (item.packageGoodsType === 0) {
            this.tempPresentList.push({
              name: item.goodsName,
              giftPieceNumber: 1,
              goodsId: item.goodsId
            })
          }
        }
        return item.packageGoodsType === 0
      })
    }
  },
  created() {
    console.log(this.$route)
    if (this.isEdit) {
      this.getInfo()
    }
    this.getAllTpl()
  },
  methods: {
    addCommon() {
      this.commonForm()
    },
    // 获取模板列表
    getAllTpl() {
      getAllList()
        .then(res => {
          if (res.code == 0) {
            this.freightList = res.data
          } else {
            this.$message({
              type: 'error',
              message: res.msg,
              duration: 2000
            })
          }
        })
        .catch(err => {
          this.$message({
            type: 'error',
            message: '未知错误',
            duration: 2000
          })
        })
    },
    getInfo() {
      this.request({
        url: '/bsnl-product/partnergoods/details',
        //url: '/partnergoods/details',
        method: 'get',
        params: {
          id: this.id,
          userId: this.$store.getters.userId
        }
      })
        .then(({ data }) => {
          data.gpackage.freightTemplateId = data.gpackage.freightTemplateId
            ? data.gpackage.freightTemplateId + ''
            : ''
          this.formData.packageRequest = data.gpackage
          this.formData.packageGalleryList = data.packageGallery
          this.formData.packageGoodsList = data.packageGoods
          this.formData.partnerGoodsDetailList = data.partnerGoodsDetail
          this.formData.partnerGoodsDetailList.map(item => {
            item.ruleJson = JSON.parse(item.ruleJson)
          })
          this.formData.partnerGoods = data.partnerGoods[0]

          this.formData.partnerGoods.selectGiftCount =
            data.partnerGoods[0].selectGiftCount || 0
          if (this.formData.partnerGoods.giftPieceNumber) {
            try {
              this.tempPresentList = JSON.parse(
                this.formData.partnerGoods.giftPieceNumber
              )
            } catch (error) {
              console.log('error', error)
            }
          }

          this.formData.buyRoleList = data.partnerGoods[0].buyRole.split(',')
          this.formData.packageGoodsList.map(item => {
            item.goodsAttr.map(
              subItem => (subItem.distributedSkuNumber = subItem.skuNumber)
            )
            this.tempGoodsCheck.push({
              id: item.id,
              goodsId: item.goodsId,
              name: item.goodsName
            })
          })
          this.commontGoods.push({
            value: data.gpackage.packageId,
            label: data.gpackage.name
          })
          // console.log(data);
          /* this.formData = {
               packageRequest: data.gpackage,
               packageGalleryList: data.packageGallery,
               packageGoodsList: data.packageGoods,
               partnerGoods: data.partnerGoods.length?data.partnerGoods[0]:{},
               partnerGoodsDetailList: data.partnerGoodsDetail,
               goodsAttr: data.goodsAttr
           };
           // console.log(this.formData);
           this.formData.packageGoodsList.map(item=>{
               item.goodsAttr.map(subItem=>subItem.distributedSkuNumber = subItem.skuNumber);
               this.tempGoodsCheck.push({
                   id: item.id,
                   goodsId: item.goodsId,
                   name: item.goodsName
               });
           });
           console.log(this.formData.packageGoodsList)*/
        })
        .catch(err => {
          console.log(err)
        })
    },
    chooseGoods() {
      this.checkGoods(this.tempGoodsCheck).then(val => {
        this.tempGoodsCheck = val
        let needDelGoods = differenceBy(
          this.formData.packageGoodsList,
          val,
          'goodsId'
        )
        let needAddGoods = differenceBy(
          val,
          this.formData.packageGoodsList,
          'goodsId'
        )
        this.formData.packageGoodsList = differenceBy(
          this.formData.packageGoodsList,
          needDelGoods,
          'goodsId'
        )
        needAddGoods.map(item => {
          this.request({
            url: '/bsnl-product/goods/details',
            method: 'get',
            params: {
              id: item.id,
              userId: this.$store.getters.userId
            }
          }).then(({ data }) => {
            let { goodsAttr } = data
            goodsAttr.map(item => (item.skuNumber = 1))
            this.formData.packageGoodsList.push({
              ...item,
              goodsName: item.name,
              goodsAttr,
              packageGoodsType: 1
            })
          })
        })
        this.$nextTick(() => {
          console.log(this.formData.packageGoodsList)
          this.$refs.form.clearValidate()
        })
      })
    },
    delGoods(index) {
      this.formData.packageGoodsList.splice(index, 1)
      this.tempGoodsCheck.splice(index, 1)
      this.reValidate()
    },
    delAttrVal(goodsAttr, index) {
      this.$confirm(`确定要删除吗?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          goodsAttr.splice(index, 1)
          this.$message.success('删除成功')
        })
        .catch(err => {
          console.log(err)
        })
    },
    // 主图上传成功
    uploadSuccess(res, file) {
      this.formData.packageRequest.image = this.replaceImgUrl(res.filePath)
      this.$refs.form.validateField('packageRequest.image')
    },
    uploadImg(event) {
      const file = event.target.files[0]
      this.picFileUpload(file, res => {
        this.formData.packageGalleryList.push({
          url: this.replaceImgUrl(res.filePath),
          type: 1
        })
        this.$refs.form.validateField('packageGalleryList')
        // this.form.packageRequest.packageGalleryList = this.form.packageGalleryList;
      })
    },
    delImg(index) {
      this.formData.packageGalleryList.splice(index, 1)
    },
    getPartnerGoodsDetailList() {
      this.formData.partnerGoodsDetailList = []
      this.formData.buyRoleList.map(item => {
        this.formData.partnerGoodsDetailList.push({
          role: item,
          type: 1,
          num: '',
          recommAreaCommission: '',
          directorCommission: '',
          recommDirectorCommission: '',
          ruleJson: {
            packageNum: '',
            presentNum: ''
          },
          bigAreas: ''
        })
        this.formData.partnerGoodsDetailList.push({
          role: item,
          type: 2,
          num: '',
          recommAreaCommission: '',
          directorCommission: '',
          recommDirectorCommission: '',
          ruleJson: {
            packageNum: '',
            presentNum: ''
          },
          bigAreas: ''
        })
      })
    },
    settingDataSpanMethod({ row, column, rowIndex, columnIndex }) {
      if (columnIndex === 0 || columnIndex === 6) {
        if (rowIndex % 2 === 0) {
          return {
            rowspan: 2,
            colspan: 1
          }
        } else {
          return {
            rowspan: 0,
            colspan: 0
          }
        }
      }
    },
    reValidate() {
      this.$refs.form.validateField('packageGoodsList')
      /*this.$refs.form.validateField('packageRequest.presentSelectedNum');
        this.$refs.form.validateField('packageGoodsList');
        this.$refs.form.validateField('packageRequest.presentSelectedNum');
        if(this.formData.packageRequest.type === 1){
            this.$refs.form.validateField('packageRequest.packageNumber');
        }else if(this.formData.packageRequest.type === 2){
            this.$refs.form.validateField('packageRequest.num');
        }*/
    },
    // 根据兰蜜价和最高佣金计算大区价和董事价
    calcPrice() {
      let query = {
        lmPrice: this.formData.packageRequest.price,
        highestCommission: this.formData.packageRequest.maximumCommission
      }
      this.calcRDPrice(query, data => {
        this.formData.packageRequest.regionPrice = data.regionPrice
        this.formData.packageRequest.directorPrice = data.directorPrice
      })
    },
    // 根据兰蜜价和最高佣金计算大区价和董事价
    calcOtherPrice(index, subIndex) {
      let query = {
        lmPrice: this.formData.packageGoodsList[index].goodsAttr[subIndex]
          .price,
        highestCommission: this.formData.packageGoodsList[index].goodsAttr[
          subIndex
        ].maximumCommission
      }
      this.calcRDPrice(query, data => {
        this.formData.packageGoodsList[index].goodsAttr[subIndex].regionPrice =
          data.regionPrice
        this.formData.packageGoodsList[index].goodsAttr[
          subIndex
        ].directorPrice = data.directorPrice
      })
    },
    save() {
      this.$refs.form.validate(valid => {
        if (!valid) {
          return false
        }
        if (this.tempPresentList.length) {
          this.formData.partnerGoods.giftPieceNumber = JSON.stringify(
            this.tempPresentList
          )
          if (this.formData.partnerGoods.selectGiftCount < 1) {
            this.$message.warning('设置赠品后,礼品数不可为0')
            return
          }
        }
        this.formData.partnerGoods.buyRole = this.formData.buyRoleList.join(',')
        this.formData.goodsAttr = []
        let noSkuGoods = []
        this.formData.packageGoodsList.map(item => {
          if (item.goodsAttr.length) {
            item.goodsAttr.map(subItem => {
              subItem.isGift = item.packageGoodsType ? 0 : 1
            })
            this.formData.goodsAttr = this.formData.goodsAttr.concat(
              item.goodsAttr
            )
          } else {
            noSkuGoods.push(item)
          }
        })
        this.formData.partnerGoodsDetailList.map((item, index) => {
          if (index % 2) {
            item.ruleJson = this.formData.partnerGoodsDetailList[
              index - 1
            ].ruleJson
          }
        })

        if (
          this.formData.goodsAttr.some(
            item => !(item.totalSkuNumber + (item.distributedSkuNumber || 0))
          )
        ) {
          this.$message.warning('存在0库存的规格商品，请先移除再保存')
        } else if (!noSkuGoods.length) {
          this.btnLoading = true
          let url = '/bsnl-product/partnergoods/create'
          if (this.isEdit) {
            url = '/bsnl-product/partnergoods/update'
          }
          this.formData.packageRequest.freightTemplateId = Number(
            this.formData.packageRequest.freightTemplateId
          )
          this.request({
            url,
            method: 'post',
            data: this.formData
          })
            .then(() => {
              if (this.isEdit) {
                this.$message.success('编辑城市合伙人套餐成功')
                this.$router.back()
                return false
              }
              this.$message.success('新建城市合伙人套餐成功')
              this.$router.push({ name: 'activityPartner' })
            })
            .catch(err => {
              console.error(err)
              this.btnLoading = false
            })
        } else {
          let msg = '商品【'
          noSkuGoods.map((item, index) => {
            msg += item.name
            msg +=
              index === noSkuGoods.length - 1
                ? '】没有SKU信息，请先移除对应的商品'
                : '、'
          })
          this.$message({
            message: msg,
            type: 'warning'
          })
        }
      })
    }
  }
}
</script>
<style lang="scss">
.partner-section {
  .el-table--medium {
    margin-top: 0 !important;
  }
  .el-table--medium tbody td {
    padding: 0;

    .el-form-item {
      margin: 22px 0;
    }
    .el-input {
      width: 100%;
    }
  }
}
</style>
